#pragma once
#include <assert.h>
class CNetPacket : public CWriterStream
{
	typedef CWriterStream super;
	static const SIZE_ST nHeaderSize = sizeof(NetPacketHeader) + sizeof(NetPacketMessage);
public:
	CNetPacket(const char* buf, SIZE_ST length)
	{
		if (length > _capacity)
			setCapacity(length);
		memcpy(_buffer, buf, length);
		_wpos = length;
		_rpos = 0;
		(*this) >> m_header;
		(*this) >> m_Msg.m_nMsgId;
		_wpos = m_header.nPackSize;
	}

	virtual void parseBuf(const char* buf, SIZE_ST length)
	{
		if (length > _capacity)
			setCapacity(length);
		memcpy(_buffer, buf, length);
		_wpos = length;
		_rpos = 0;
		(*this) >> m_header;
		(*this) >> m_Msg.m_nMsgId;
		_wpos = m_header.nPackSize;
	}

	CNetPacket(unsigned short sysId, unsigned short cmd) :m_Msg(sysId, cmd)
	{
		setCapacity(MAX_LENGTH);
		m_header.nPackSize = 0;
		_wpos = nHeaderSize;
		m_fd = 0;
	}
	CNetPacket(int msgId) :m_Msg(msgId)
	{
		setCapacity(MAX_LENGTH);
		m_header.nPackSize = 0;
		_wpos = nHeaderSize;
		m_fd = 0;
	}
	~CNetPacket()
	{
		clear();
	}

	void fixMsgHeader()
	{
		m_header.nPackSize += this->length();
		SIZE_ST oldWpos = _wpos;
		_wpos = 0;
		(*this) << nHeaderFlag;
		(*this) << m_header.nPackSize;
		(*this) << m_Msg.m_nMsgId;
		_wpos = oldWpos;
	}
	static void _Flush_Packet(CNetPacket& t)
	{
		t.fixMsgHeader();
		if (t.m_fd)
		{
			int err = send((SOCKET)t.m_fd, t.c_str(), t.length(), 0);
			if (err == SOCKET_ERROR)
			{
				assert(false);
			}
		}


		t.clear();
	}
public:
	NetPacketHeader m_header;
	NetPacketMessage m_Msg;
	evutil_socket_t m_fd;
};

#define Flush_Packet(t) CNetPacket::_Flush_Packet(t)